﻿/*********************************************************
 * 项目：
 * 描述：
 * 作者：英夫美迪 冯东耀 simadi@qq.com
 * 日期：2012/7/4 14:08:14
 * *******************************************************/

using System;
using System.Collections.Generic;
using System.Configuration;
using Entity.QQ;

namespace Common
{
    public class QQService : HttpMethods
    {
        #region 字段
        /// <summary>
        /// App Key
        /// </summary>
        public string AppKey { get; set; }
        /// <summary>
        /// App Secret
        /// </summary>
        public string AppSecret { get; set; }

        public AccessToken AccessToken { get; set; }
        string CallBackUrl { get; set; }

        public string OpenId { get; set; }

        #endregion
        /// <summary>
        /// 构造函数
        /// </summary>
        public QQService()
        {
            var keyAndSecret = ConfigurationManager.AppSettings["KeySecretQQ"]; //从配置文件中获取AppKey, AppSecret
            CallBackUrl =Util.GetHost()+ConfigurationManager.AppSettings["CallBackUrlQQ"];//从配置文件中获取回调地址
            var arrayAppKeyAppSecret = keyAndSecret.Split(':');
            AppKey = arrayAppKeyAppSecret[0];
            AppSecret = arrayAppKeyAppSecret[1];
        }

        #region token相关

        public string GetCodeUrl()
        {
            var dictionary = new Dictionary<object, object>
                {
                    {"client_id",AppKey},
                    {"response_type","code"},
                    {"redirect_uri",CallBackUrl}
                };
            return string.Format("{0}?{1}", QqUrls.Authorize,dictionary.ToQueryString() );
        }
        /// <summary>
        /// 获取Request Token
        /// 默认 Http 方法为 GET
        /// </summary>
        /// <returns></returns>
        public AccessToken GetAccessToken(string code)
        {
            var dictionary = new Dictionary<object, object>
                {
                    {"client_id",AppKey},
                    {"client_secret",AppSecret},
                    {"grant_type","authorization_code"},
                    {"redirect_uri",CallBackUrl},
                    {"code",code}
                };
            var url = string.Format("{0}?{1}", QqUrls.AccessToken, dictionary.ToQueryString());
            var result = HttpPost(url);//取到的字符串 需要拼成json
            //Util.LogFile("qqToken" + result);
            var jsonString = @"{""" + result.Replace("&", @""",""").Replace("=", @""":""") + @"""}";
            return jsonString.ToEntity<AccessToken>();
        }
        #region 刷新token
        public AccessToken RefreshToken(string refreshToken)
        {
            //https://open.t.qq.com/cgi-bin/oauth2/access_token?client_id=APP_KEY&client_secret=APP_SECRET&grant_type=refresh_token&refresh_token=REFRESH_TOKEN 
            var dictionary = new Dictionary<object, object>
            {  
                {"client_id",AppKey},
                {"client_secret",AppSecret},
                {"grant_type","refresh_token"},
                {"refresh_token",refreshToken}
            };

            var url = string.Format("{0}?{1}", QqUrls.AccessToken, dictionary.ToQueryString());
            var result = HttpPost(url);//取到的字符串 需要拼成json
            var jsonString = @"{""" + result.Replace("&", @""",""").Replace("=", @""":""") + @"""}";
            return jsonString.ToEntity<AccessToken>();
        }
        #endregion
        #endregion

        #region 发布一条微博 可上传图片

        /// <summary>
        /// 发布一条新微博上传图片并
        /// </summary>
        /// <param name="content">要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。</param>
        /// <param name="pic">要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。</param>
        ///<param name="reid">要评论的微博id,默认为0,即新发的</param>
        ///<param name="clientip">客户端ip</param>
        ///<returns></returns>
        public StatusResult Post(string token,string openId,string content, byte[] pic = null, long reid = 0,string clientip="")
        {
            content = content.Length > 140 ? content.Substring(0, 140) : content;
            var dictionary = new Dictionary<object, object>
            {  
                {"oauth_consumer_key",AppKey},
                {"access_token",token},
                {"openid",openId},
                {"clientip",clientip},
                {"oauth_version","2.a"},
                {"scope","all"},
                //以上为oauth部分
                {"format","json"},
                {"content",Uri.EscapeDataString(content)},
                {"jing",""},
                {"wei",""}
            };
            if (reid > 0)
            {
                return RePost(reid, dictionary);//转播
            }
            string jsonString;
            if (pic == null || pic.Length == 0)
                jsonString=HttpPost(QqUrls.Update, dictionary.ToQueryString());
            else
            {
                dictionary.Remove("content");
                dictionary.Add("content",content);
                jsonString = HttpPost(QqUrls.Upload, dictionary, pic);
            }
            //Util.LogFile(jsonString);
            return jsonString.ToEntity<StatusResult>();
        }
        #endregion

        #region 转播一条微博
        /// <summary>
        /// 转播一条微博
        /// </summary>
        /// <param name="dictionary"></param>
        /// <returns>转播结果</returns>
        public StatusResult RePost(long reid, Dictionary<object, object> dictionary)
        {
            return Comment(reid, dictionary, QqUrls.Repost);
        }
        #endregion

        #region 评论一条微博
        /// <summary>
        /// 评论一条微博
        /// </summary>
        /// <param name="dictionary"></param>
        /// <returns> 评论结果</returns>
        public StatusResult Comment(long reid, Dictionary<object, object> dictionary,string url=QqUrls.Comment)
        {
                dictionary.Add("reid", reid);
            var jsonString = HttpPost(url, dictionary.ToQueryString());
            //Util.LogFile(jsonString);
            return jsonString.ToEntity<StatusResult>();
        }

        #endregion

        #region 获取自己的资料
        /// <summary>
        /// 采用默认API请求地址获取用户本人帐号信息
        /// </summary>
        /// <returns>本人帐号信息.</returns>
        public UserInfo GetMyInfo(string token,string openId)
        {
            var dictionary = new Dictionary<object, object>
            {  
                {"oauth_consumer_key",AppKey},
                {"access_token",token},
                {"openid",openId},
                {"oauth_version","2.a"},
                {"scope","all"},
                {"format","json"}
            };
            string jsonString = HttpPost(QqUrls.GetUserInfo, dictionary.ToQueryString());
            return jsonString.ToEntity<UserInfo>();
        }
        #endregion

        #region 我发表时间线
        /// <summary>
        /// 采用默认API请求地址获取我发表时间线
        /// </summary>
        /// <param name="pageflag">分页标识 0：第一页，1：向下翻页，2：向上翻页</param>
        /// <param name="pagetime">本页起始时间（第一页：填0，向上翻页：填上一次请求返回的第一条记录时间，向下翻页：填上一次请求返回的最后一条记录时间</param>
        /// <param name="reqnum">每次请求记录的条数（1-200条）</param>
        /// <param name="lastid">和pagetime配合使用（第一页：填0，向上翻页：填上一次请求返回的第一条记录id，向下翻页：填上一次请求返回的最后一条记录id</param>
        /// <returns>获取我发表的微博</returns>
        public TimelineInfo GetMyTimeline(string token,string openId,long pagetime, int reqnum, long lastid)
        {
            var dictionary = new Dictionary<object, object>
                {
                    {"oauth_consumer_key",AppKey},
                    {"access_token",token},
                    {"openid",openId},
                    {"oauth_version","2.a"},
                    {"scope","all"},
                    //以上为oauth部分
                    {"format","json"},
                    {"pageflag", 0},
                    {"pagetime", pagetime.ToString()},
                    {"reqnum", reqnum.ToString()},
                    {"lastid", lastid.ToString()},
                    {"type", "0x1"},//0x1 原创发表,0x2 转载,0x8 回复,0x10 空回,0x20 提及,0x40 点评,如需拉取多个类型请使用|，如(0x1|0x2)得到3，则type=3即可，填零表示拉取所有类型 
                    {"contenttype", "0"}//0-表示所有类型，1-带文本，2-带链接，4-带图片，8-带视频，0x10-带音频 
                };
            var url = string.Format("{0}?{1}", QqUrls.UserTimeline, dictionary.ToQueryString());
            var jsonString = HttpGet(url);
            Util.CreatFile("my.txt", jsonString);
            return jsonString.ToEntity<TimelineInfo>();
        }
        #endregion
    }
}
